package com.idea.relax.log.appender.kafka;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;

/**
 * @author salad
 * @date: 2022/12/17
 * @description: KafkaAppender
 */
@Slf4j
@AllArgsConstructor
public class KafkaAppender extends AppenderBase<ILoggingEvent> {

    private final String topic;

    private final KafkaTemplate<String, String> kafkaTemplate;

    @Override
    public void start() {
        //这里啥都不需要做
    }

    @Override
    protected void append(ILoggingEvent eventObject) {
        String message = eventObject.getFormattedMessage();
        String key = eventObject.getLevel().levelStr;
		if (log.isDebugEnabled()) {
			log.debug("Start pushing logs to kafka: key=" + key + ",message=" + message);
		}
        try {
            //生产消息
            kafkaTemplate.send(topic, key, message);
        } catch (Exception e) {
            log.error("kafka send log failure!", e);
        }
    }

}
